package com.heima;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();

        // 定义四个点并命名
        double[][] points = {
                {119.037089, 32.259867},  // P1
                {118.821489, 32.077388},  // P2
                {118.80657099, 32.0353893},  // P3
                {118.894173, 32.077862}   // P4
        };
        String[] pointNames = {"P1", "P2", "P3", "P4"};

        try {
            // 读取JSON文件并映射到List<List<Double>>对象
            List<List<Double>> polygonPoints = objectMapper.readValue(
                    new File("F:\\javaproject\\untitled\\src\\main\\java\\com\\latlon.json"),
                    new TypeReference<List<List<Double>>>() {}
            );

            // 判断每个点是否在多边形内，并按指定格式输出结果
            for (int i = 0; i < points.length; i++) {
                double x = points[i][0];
                double y = points[i][1];
                String pointName = pointNames[i];

                if (isPointInPolygon(x, y, polygonPoints)) {
                    System.out.println(pointName + " is inside the polygon.");
                } else {
                    System.out.println(pointName + " is outside the polygon.");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断点(x, y)是否在多边形内
     * 使用射线法
     */
    public static boolean isPointInPolygon(double x, double y, List<List<Double>> polygon) {
        int intersectCount = 0;
        int size = polygon.size();
        double lastX = polygon.get(size - 1).get(0), lastY = polygon.get(size - 1).get(1);
        boolean isLastInside = (lastY > y);

        for (int i = 0; i < size; ++i) {
            double curX = polygon.get(i).get(0), curY = polygon.get(i).get(1);
            boolean isCurInside = (curY > y);

            if (isCurInside == isLastInside) {
                lastX = curX;
                lastY = curY;
                continue;
            }

            double intersectionX = lastX + (y - lastY) * (curX - lastX) / (curY - lastY);
            if (intersectionX > x) {
                intersectCount++;
            }

            lastX = curX;
            lastY = curY;
            isLastInside = isCurInside;
        }

        return intersectCount % 2 != 0;
    }
}